package com.tsd.core.mybatis;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tsd.core.utils.ExceptionUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * <columnOverride column="urls" javaType="java.lang.String" typeHandler="com.tsd.core.mybatis.JsonStringArrayTypeHandler"/>
 *
 * @author Hillpool
 */
public class FastJsonListStringTypeHandler extends BaseTypeHandler<List<String>> {

    public static final Logger LOGGER = LoggerFactory.getLogger(FastJsonListStringTypeHandler.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, this.toJson(parameter));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex));
    }

    private String toJson(List<String> params) {
        try {
            return JSON.toJSONString(params);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        }
        return "[]";
    }

    private List<String> toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                return JSON.parseArray(content, String.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return new ArrayList<>();
        }
    }
}